/**
 * @file 所有工具类函数
 * @author haoxubin
 */
import {getCookie, saveCookie, signOut} from '@/auth/authService';
import * as api from '@/api';

export function base2file(dataURI, type) {
    const binary = atob(dataURI.split(',')[1]);
    const array = [];
    for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    const $Blob = new Blob([new Uint8Array(array)], {type});
    return $Blob;
}

export const login = {
    loginInfo: {
        flag: 'haha',
        error_msg: null,
        token: null,
        user: null
    },
    async logout() { // 登出
        return signOut();
    },
    async localLogin(userInfo) {
        return api.localLogin(userInfo).then((response) => {
            if (!response.ok) {
                const msg = response.data.error_msg || '登录失败';
                return Object.assign({}, this.loginInfo, {error_msg: msg});
            }
            let Token = response.data.token; // 获取TOKEN
            saveCookie('token', Token);
            Token = getCookie('token') || null;
            return Object.assign({}, this.loginInfo, {token: Token});
        });
    },
    async getUserInfo() {
        console.log('获取用户信息');
        return api.getMe().then((response) => {
            // console.log(response);
            if (!response.ok) {
                const msg = response.data.error_msg || '用户信息获取失败';
                return Object.assign({}, this.loginInfo, {error_msg: msg});
            }
            const userInfo = response.data;
            return Object.assign({}, this.loginInfo, {user: userInfo});
        });
    },
    async updateUser(store, userInfo) {
        api.mdUser(userInfo).then((response) => {
            if (!response.ok) {
                const msg = '更新用户资料失败!';
                return Object.assign({}, this.loginInfo, {error_msg: msg});
            }
            this.loginInfo.user = response.data.data;
            return this.loginInfo;
        }, (response) => {
            console.log(response.data.error_msg);
            const msg = '更新用户资料失败!';
            return Object.assign({}, this.loginInfo, {error_msg: msg});
        });
    }
};
